package com.goodluck.goodluckim.utils;

import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.goodluck.goodluckim.BuildConfig;
import com.goodluck.goodluckim.ui.IMApplication;

/**
 * 全局的toast显示的工具类
 */
public class ToastUtil {
    private static Toast mToast;
    private static Handler mHandler;

    /**
     * 取消mToast引用对象
     */
    public static void destroy() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        mToast = null;
    }

    /**
     * 默认toast的显示
     *
     * @param resId 提示内容的资源id
     */
    public static void toast(int resId) {
        toastNow(IMApplication.getApplication().getResources().getText(resId), Toast.LENGTH_SHORT);
    }

    /**
     * 默认toast的显示
     *
     * @param content 提示内容
     */
    public static void toast(CharSequence content) {
        toastNow(content, Toast.LENGTH_SHORT);
    }

    /**
     * 指令返回结果的toast提示
     *
     * @param content 提示内容
     * @param code    错误状态字
     */
    public static void toast(String content, int code) {
        if (!BuildConfig.BUILD_TYPE.equals("release")) {
            toastNow(content + "，code：" + code, Toast.LENGTH_SHORT);
        } else {
            if (content != null && content.trim().length() > 0) {
                toastNow(content, Toast.LENGTH_SHORT);
            }
        }
    }

    private static void toastNow(final CharSequence content, final int duration) {
        // 主线程
        if (Looper.myLooper() == Looper.getMainLooper()) {
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = Toast.makeText(IMApplication.getApplication(), content, duration);
            mToast.show();
            return;
        }
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(IMApplication.getApplication(), content, duration);
                mToast.show();
            }
        });
    }
}